﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace AlternativePorts
{
	public static class PortExtensions
	{
		public static T ReceiveSync<T>(this Port<T> port)
		{
			return port.ReceiveSync(Timeout.Infinite);
		}

		public static T ReceiveSync<T>(this Port<T> port, int timeout)
		{
			ManualResetEvent ev = new ManualResetEvent(false);
			T item = default(T);
			port.RegisterReceiver(x => 
			{
				item = x;
				ev.Set();
				port.UnregisterReceiver();
			}, ReceiveMode.Sequential);

			if (!ev.WaitOne(timeout))
				throw new TimeoutException("No message arrived on Port until timeout!");
			return item;
		}
	}
}
